package com.bjpowernode.pay.controller;

import com.bjpowernode.api.model.User;
import com.bjpowernode.api.serivce.UserService;
import com.bjpowernode.constants.RedisKey;
import com.bjpowernode.pay.service.RechargeKuaiQianService;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Map;

/**
 * @author 麦翔盛
 * @ClassName: RechargeController
 * @Package: com.bjpowernode.pay.controller
 * @description: 充值接口
 * @date 2022/5/30 22:39
 */
@Controller
@CrossOrigin
public class RechargeController {

    @DubboReference(interfaceClass = UserService.class, version = "1.0")
    private UserService userService;

    @Resource
    private RechargeKuaiQianService rechargeKuaiQianService;


    @GetMapping("/recharge/kq/request")
    public String receiveRecharge(@RequestParam("uid") Integer uid,
                                  @RequestParam("rechargeMoney") BigDecimal rechargeMoney,
                                  @RequestParam("channel") String channel,
                                  Model model) {
        //返回的视图
        String viewName = "err";
        //校验数据
        if ((uid != null && uid > 0)) {
            if (rechargeMoney != null && rechargeMoney.doubleValue() > 0) {
                try {
                    //获取用户信息
                    User user = userService.queryUserById(uid);
                    if (user != null) {
                        //保存数据到视图
                        Map<String, String> params =
                                rechargeKuaiQianService.generateFormData(user.getPhone(), uid, rechargeMoney);
                        model.addAttribute(params);

                        //创建新的订单
                        boolean add =
                                rechargeKuaiQianService.generateNewOrder(uid, params.get("orderId"), rechargeMoney, channel);

                        //将订单保存到redis中
                        if( add ){
                            rechargeKuaiQianService.addToRedis(params.get("orderId"));
                            model.addAllAttributes(params);
                            viewName = "rechargeForm";
                        }else{

                        }

                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }
        }

        return viewName;
    }
}
